package handler

import (
	"class/api/request"
	"class/glodal"
	"class/inits"
	"class/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"net/http"
	"strconv"
	"time"
)

func VideoList(c *gin.Context) {
	var video []model.Video
	glodal.DB.Find(&video)
	marshal, err := json.Marshal(video)
	if err != nil {
		return
	}
	glodal.Rdb.Set(inits.Ctx, "video", marshal, time.Hour*2)
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查询成功",
		"data":    video,
	})
}

func VideoShow(c *gin.Context) {
	var req request.Video
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	var videos model.Video
	glodal.DB.Where("id = ?", req.VideoId).First(&videos)
	marshal, err := json.Marshal(videos)
	if err != nil {
		return
	}
	glodal.Rdb.Set(inits.Ctx, "videoShow", marshal, time.Hour*2)
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查询成功",
		"data":    videos,
	})

}

func VideoP(context *gin.Context) {
	var req request.VideoP
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	var video []model.Video
	glodal.DB.Order("likes desc").Limit(10).Find(&video)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看成功",
		"data":    video,
	})

}
func VideoCreate(context *gin.Context) {
	videoId := context.Query("videoId")
	likes := context.Query("likes")
	float, err := strconv.ParseFloat(likes, 64)
	if err != nil {
		return
	}
	glodal.Rdb.ZAdd(inits.Ctx, "videoPai", &redis.Z{
		Score:  float,
		Member: videoId,
	})
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "添加成功",
	})
}
